vLastLootCheck = nil
bPauseAutoLoot = false
local vFrameCount = 0

function AutoLoot()
	if ccRS.Auto_Loot then
		if not frAutoLoot then
			frAutoLoot = CreateFrame("Frame");
			frAutoLoot:SetFrameStrata("TOOLTIP");
			frAutoLoot:Show();
			frAutoLoot:SetWidth(1);
			frAutoLoot:SetHeight(1);
			frAutoLoot:SetScript("OnUpdate", frAutoLoot_OnUpdate);
			frAutoLoot:SetScript("OnEvent", frAutoLoot_OnEvent);
			frAutoLoot:RegisterEvent("LOOT_OPENED")
			frAutoLoot:RegisterEvent("LOOT_CLOSED")
		end
	else
		if frAutoLoot then
			frAutoLoot:SetScript("OnUpdate", nil);
			frAutoLoot:SetScript("OnEvent", nil);
		end
	end
end

function frAutoLoot_OnUpdate(self, elapsed)
	if ccRS.Auto_Loot
	and not ccrPlayerIsMoving()
	and not ccrPlayerIsInCombat()
	and not ccrPlayerIsDead()
	and not ccrPlayerIsCastingOrChanneling()
	and GetNumLootItems() == 0
	and (vFrameCount == nil or vFrameCount >= 100)
	then
		if vLastLootCheck == nil
		or (GetTime() - vLastLootCheck) > 1
		then
			vLastLootCheck = GetTime()
			CheckAreaForLoot()
		end
		vFrameCount = 0
	else
		vFrameCount = vFrameCount + 1
	end
end

function frAutoLoot_OnEvent(self, event, arg1)
	if event == "LOOT_OPENED" then
		bPauseAutoLoot = true
		vLootCount = GetNumLootItems()
		if vLootCount > 0 then
			for i = 1, vLootCount do
				vLootInfo = {GetLootSlotInfo(i)}
				if vLootInfo[5] ~= 1 then
					LootSlot(i);
					ConfirmLootSlot(i);
				end
			end
		end
		if vLootCount == 0 then bPauseAutoLoot = false end;
	end
	if event == "LOOT_CLOSED" then
		bPauseAutoLoot = false
	end
end

function CheckAreaForLoot()
	if ccrPlayerIsCastingOrChanneling() then return end
	if # ccrObjectListTable == nil then return end;
	for i = 0, # ccrObjectListTable do
		local tblObject = ccrObjectListTable[i]
		if tblObject ~= nil
		and tblObject:Exists()
		and tblObject:GetType() == 3
		and tblObject:GetDistance() <= max(5, (13 / 6) + tblObject:GetCombatReach())
		and not bPauseAutoLoot
		--and not ccrPlayerIsInStealth()
		and GetNumLootItems() == 0
		then
			if tblObject:IsLootable() then
				tblObject:Interact()
			end
			if tblObject:IsSkinnable() then
				tblObject:Interact()
			end
			vLastLootCheck = GetTime()
		end
	end	
end
